package com.demo.cms.action.manage;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.demo.cms.model.Article;
import com.demo.cms.model.Category;
import com.demo.cms.model.Channel;
import com.demo.cms.model.Navi;
import com.demo.cms.service.ArticleService;
import com.demo.cms.service.CategoryService;
import com.demo.cms.service.ChannelService;
import com.demo.cms.service.NaviService;
import com.demo.common.StringUtils;
import com.demo.core.dao.base.support.ResultSearchResult;
import com.demo.core.model.Role;
import com.demo.core.model.Site;
import com.demo.core.model.support.AdjacencyListModel;
import com.demo.core.service.base.RoleService;
import com.demo.core.util.collection.JsonUtils;
import com.demo.security.annotation.function.Function;
import com.demo.webapp.action.PageAction;

/**
 * 导航管理的Action
 * 
 * @author ryuu.kk
 *
 */
@Function(id = 108200, pid = 10, code = "manage.navi")
public class NaviAction extends PageAction {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = -6525752375823942510L;
	
	/**
	 * 导航ID
	 */
	private Long id;
	
	/**
	 * 导航上级ID
	 */
	private Long pid;
	
	/**
	 * 自动生成类型
	 */
	private String type;
	
	/**
	 * 导航列表
	 */
	private List<Navi> naviList;
	
	/**
	 * 角色列表
	 */
	private List<Role> roleList;
	
	/**
	 * 导航模型
	 */
	private Navi navi;
	
	/**
	 * 导航树的json字符串
	 */
	private String json;
	
	/**
	 * 导航模型(树结构)
	 */
	private AdjacencyListModel tree;
	
	/**
	 * 导航服务接口
	 */
	private NaviService naviService;
	
	/**
	 * 角色服务接口
	 */
	private RoleService roleService;
	
	/**
	 * 频道服务
	 */
	private ChannelService channelService;
	
	/**
	 * 栏目服务
	 */
	private CategoryService categoryService;
	
	/**
	 * 文章服务
	 */
	private ArticleService articleService;
	
	/**
	 * 频道服务
	 */
	private List<Channel> channelList;
	
	/**
	 * 栏目服务
	 */
	private List<Category> categoryList;
	
	/**
	 * 文章服务
	 */
	private List<Article> articleList;
	
	/**
	 * 导航一览
	 * @return String
	 */
	@Function(id = 108210, pid = 108200, code = "manage.naviAction.list")
	public String list() {
		// 取得站点ID
		Site site = getSite();
		
		// 生成导航树
		//tree();
		
		// 取得频道列表(用户生成地址)
		this.channelList = channelService.findList(site.getId());
		// 使用分页查询
		//this.naviList = naviService.findList(site.getId(), this.id);
		ResultSearchResult<Navi> resultSupport = naviService.search(site.getId(), this.id, getArgumentSupport());
		super.setResultSupport(resultSupport);
		this.naviList = new ArrayList<Navi>(resultSupport.getResults());
		return SUCCESS;
	}
	
	/**
	 * 创建导航
	 * @return String 
	 */
	@Function(id = 108220, pid = 108200, code = "manage.naviAction.create")
	public String create() {
		
		// 取得站点ID
		Site site = getSite();
				
		permission();
		
		// 取得频道列表(用户生成地址)
		this.channelList = channelService.findList(site.getId());
		
		// 找到导航列表
		naviList = naviService.findList(site.getId(), null);
		
		return SUCCESS;
	}
	
	/**
	 * 保存导航
	 * @return String
	 */
	@Function(id = 108230, pid = 108200, code = "manage.naviAction.save")
	public String save() {
		// 取得站点ID
		Site site = getSite();
		// 设置站点组ID
		navi.setSiteId(site.getId());
		if (!navi.isAnonymous() && roleList != null) {
			navi.setRoleList(roleList);
		}
		
		naviService.save(navi);
		addActionMessage(getText("navi.added", "导航已创建", navi.getTitle()));
		// function.setType(type)
		return CALLBACK;
	}
	
	@Function(id = 108240, pid = 108200, code = "manage.naviAction.edit")
	public String edit() {
		
		// 取得站点ID
		Site site = getSite();
				
		permission();
		
		// 取得频道列表(用户生成地址)
		this.channelList = channelService.findList(site.getId());
		
		// 找到导航列表
		naviList = naviService.findList(site.getId(), null);
				
		if (id != null) {
			this.navi = naviService.find(id);
		}
		
		// 获得栏目列表
		if (navi != null && navi.getChannelId() != null) {
			this.categoryList = categoryService.findList(navi.getChannelId());
		}
		// 获得文章列表
		if (navi != null && navi.getCategoryId() != null) {
			this.articleList = articleService.findList(navi.getCategoryId(), null);
		}
		return SUCCESS;
	}
	
	/**
	 * 功能更新
	 * @return String 
	 */
	@Function(id = 108250, pid = 108200, code = "manage.naviAction.update")
	public String update() {
		// 更新功能模型
		naviService.update(id, navi);
		naviService.update(id, navi.isEnabled(), "RWD");
		addActionMessage(getText("navi.updated", "导航已更新", navi.getTitle()));
		return CALLBACK;
	}
	
	/**
	 * 删除功能信息
	 * 
	 * @return String
	 */
	@com.demo.security.annotation.function.Function(id = 108260, pid = 108200, code = "manage.function.delete")
	public String delete() {

		naviService.delete(id);
		addActionMessage(getText("navi.deleted", "导航已删除"));
		return CALLBACK;
	}
	
	/**
	 * 批量删除
	 * @return
	 */
	@Function(id = 108270, pid = 108200, code = "manage.naviAction.rm")
	public String rm() {
		if (naviList != null && naviList.size() > 0) {
			for (Navi m : naviList) {
				naviService.delete(m.getId());				
			}
		}
		addActionMessage(getText("navi.deleted", "导航已删除"));
		return CALLBACK;
	}
	
	/**
	 * 导航自动生成页面
	 * @return String
	 */
	public String auto() {
		
		return SUCCESS;
	}
	
	/**
	 * 导航生成处理
	 * @return String
	 */
	public String gen() {
		// 取得站点ID
		Site site = getSite();
		Long siteId = site.getId();
				
		if (StringUtils.isNotEmpty(type)) {
			if ("custom".equals(type)) {
				channelList = channelService.findList(siteId);
			} else {
				if (pid != null) {
					channelList = new ArrayList<Channel>();
					Channel channel = channelService.find(id);
					channelList.add(channel);
				}
			}
			
			if(!naviService.exists(1L)) {
				//致我们终将逝去的青春
				navi = naviService.getDefaultModel(siteId);
				navi.setId(1L);
				navi.setPid(null);
				pid = naviService.save(navi);
			}
			
			// 查找根节点
			navi = naviService.find(1L);
			pid = navi.getId();
			if (channelList != null) {
				for (Channel chn : channelList) {
					// 创建频道导航
					navi.setId(null);
					navi.setPid(pid);
					navi.setTitle(chn.getTitle());
					navi.setName(chn.getPath());
					navi.setChannelId(chn.getId());
					navi.setCategoryId(null);
					navi.setArticleId(null);
					navi.setAnonymous(Boolean.TRUE);
					navi.setEnabled(Boolean.TRUE);
					id = naviService.save(navi);
					AdjacencyListModel root = categoryService.queryRootTree(chn.getId());
					if (root != null) {
						// 忽略栏目根
						List<AdjacencyListModel> nodes = root.getChilds();
						if (nodes != null) {
							for (AdjacencyListModel node : nodes) {
								doNode(navi, id, (Category)node, node.getChilds());
							}
						}
					}
				}
			}
			
			addActionMessage(getText("navi.generate", "导航自动生成已完成."));
		}
		return CALLBACK;
	}
	
	/**
	 * 查找导航的访问许可
	 * @return
	 */
	public String permission() {
		// 取得站点ID
		Site site = getSite();
		Long siteId = site.getId();
		List<Role> roleList = roleService.findList(siteId);
		Set<Long> keySet = new HashSet<Long>();
		if (id != null && id > 0L) {
			Navi navi = naviService.query(siteId, id);
			if (navi != null) {
				List<Role> rl = navi.getRoleList();
				if (roleList != null) {
					for (Role r : rl) {
						keySet.add(r.getId());
					}
				}
			}
		}

		this.json = "{'items':[";
		StringBuffer sb = new StringBuffer();
		String format = "{id:\'%d\', name:\'%s\', title:\'%s\', enabled:\'%s\', isPermission:\'%s\'},";
		
		for (Role r : roleList) {
			sb.append(String.format(format, r.getId(), r.getName(), r.getTitle(), r.getEnabled(), keySet.contains(r.getId())));	
		}
		this.json += sb.toString().substring(0, sb.length() - 1) + "]}";
		return SUCCESS;
	}
	/**
	 * 导航树
	 * @return String
	 */
	public String tree() {
		// 取得站点ID
		Site site = getSite();
		if (id != null) {
			// 站点最大功能集合(Tree),功能树下的所有
			this.tree = naviService.queryTree(site.getId(), id, null);
		} else {
			// 站点最大功能集合(Tree),站点所有功能
			this.tree = naviService.queryTree(site.getId());
		}
		
		// 生成json树,展开级别:2
		json = JsonUtils.zTree(tree, 2);
		return SUCCESS;
	}
	
	/**
	 * 加入导航节点
	 * @param navi 导航模型
	 * @param pid 父亲ID
	 * @param root 数据的ROOT
	 * @param nodes 数据ROOT的子节点
	 */
	private void doNode(Navi navi, Long pid, Category root, List<AdjacencyListModel> nodes) {
		
		navi.setId(null);
		navi.setPid(pid);
		navi.setChannelId(root.getChannelId());
		navi.setCategoryId(root.getId());
		navi.setTitle(root.getTitle());
		navi.setName(root.getName());
		Long id = naviService.save(navi);
		if (nodes != null) {
			for (AdjacencyListModel node : nodes) {
				doNode(navi, id, (Category)node, node.getChilds());
			}
		}
	}
	
	// ~ settings here --------------------------------------------------------

	public void setNaviService(NaviService naviService) {
		this.naviService = naviService;
	}
	
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public void setChannelService(ChannelService channelService) {
		this.channelService = channelService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public void setArticleService(ArticleService articleService) {
		this.articleService = articleService;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getPid() {
		return pid;
	}

	public void setPid(Long pid) {
		this.pid = pid;
	}

	public void setType(String type) {
		this.type = type;
	}
	
	public void setNavi(Navi navi) {
		this.navi = navi;
	}

	public Navi getNavi() {
		return navi;
	}

	public List<Navi> getNaviList() {
		return naviList;
	}

	public void setNaviList(List<Navi> naviList) {
		this.naviList = naviList;
	}

	public List<Role> getRoleList() {
		return roleList;
	}

	public void setRoleList(List<Role> roleList) {
		this.roleList = roleList;
	}

	public List<Channel> getChannelList() {
		return channelList;
	}

	public List<Category> getCategoryList() {
		return categoryList;
	}

	public List<Article> getArticleList() {
		return articleList;
	}

	public AdjacencyListModel getTree() {
		return tree;
	}

	public String getJson() {
		return json;
	}
}
